package src.queries;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import  src.entities.RadRecord;
import src.entities.User;

public class SecurityQueries extends QueryFactory{

	public SecurityQueries(Connection c) {
		super(c);
	}
	
	
	public ArrayList<RadRecord> isViewable(ArrayList<RadRecord> searchResults, User currentUser){
		String userClass = currentUser.getUserClass();
		
		if(userClass.equals("p"))
			return patientViewable(searchResults, currentUser);
		else if(userClass.equals("d"))
			return doctorViewable(searchResults, currentUser);
		else if(userClass.equals("r"))
			return radiologistViewable(searchResults, currentUser);
		else if(userClass.equals("a"))
			return searchResults;
		
		return null;
	}

	private ArrayList<RadRecord> doctorViewable(
			ArrayList<RadRecord> searchResults, User currentUser) {
		ArrayList<RadRecord> newResults = new ArrayList<RadRecord>();
		
		
		
		for(RadRecord record: searchResults){
			if(record.getPatientName().equals(currentUser.getUserName())){
				newResults.add(record);
			}
			else if(record.getDoctorName().equals(currentUser.getUserName())){
				newResults.add(record);
			}
			else{
				PreparedStatement ps;
				try {
					ps = makePreparedStatement("SELECT COUNT(*)" +
							" FROM family_doctor" +
							" WHERE doctor_name = ?" +
							" AND patient_name = ?");
					ps.setString(1, currentUser.getUserName());
					ps.setString(2, record.getPatientName());
					
					ResultSet rs = ps.executeQuery();
					rs.next();
					if(rs.getInt(1) > 0){
						newResults.add(record);
					}
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
		}
		
		return newResults;
	}


	private ArrayList<RadRecord> radiologistViewable(
			ArrayList<RadRecord> searchResults, User currentUser) {
		
		ArrayList<RadRecord> newResults = new ArrayList<RadRecord>();
		
		for(RadRecord record: searchResults){
			if(record.getPatientName().equals(currentUser.getUserName())){
				newResults.add(record);
			}
			else if(record.getRadiologistName().equals(currentUser.getUserName())){
				newResults.add(record);
			}
		}
		
		return newResults;
		
	}


	public boolean isDoctor(String doctorName) throws SQLException {
		PreparedStatement p = makePreparedStatement(
		"Select count(*) FROM users " +
		"WHERE user_name = ? AND class = 'd'");

		p.setString(1, doctorName);
		ResultSet rs = p.executeQuery();
		rs.next();
		if(rs.getInt("COUNT(*)") > 0){
			return true;
		}
		return false;
	}
	
	private ArrayList<RadRecord> patientViewable(ArrayList<RadRecord> searchResults, User currentUser){
		
		ArrayList<RadRecord> newResults = new ArrayList<RadRecord>();
		
		for(RadRecord record: searchResults){
			if(record.getPatientName().equals(currentUser.getUserName()))
				newResults.add(record);
		}
		
		return newResults;
	}
}
